package com.coursehub.course.service.impl;

import com.coursehub.course.entity.Material;
import com.coursehub.course.repository.MaterialRepository;
import com.coursehub.course.service.MaterialService;
import com.coursehub.shared.exception.ResourceNotFoundException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.coursehub.shared.client.ServiceClient;

import java.io.File;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MaterialServiceImpl implements MaterialService {
    
    private static final Logger log = LoggerFactory.getLogger(MaterialServiceImpl.class);
    
    private final MaterialRepository materialRepository;
    private final ServiceClient serviceClient;
    
    @Value("${coursehub.services.urls.learning-progress:http://localhost:8085}")
    private String learningProgressServiceUrl;
    
    @Override
    @Transactional
    public Material uploadMaterial(Material material) {
        log.info("上传资料: {}", material.getMaterialName());
        return materialRepository.save(material);
    }
    
    @Override
    public List<Material> getMaterialByChapter(String chapterId) {
        log.info("根据章节ID获取资料: {}", chapterId);
        return materialRepository.findByChapter_ChapterId(chapterId);
    }
    
    @Override
    public List<Material> getMaterialByCourseId(String courseId) {
        log.info("根据课程ID获取资料: {}", courseId);
        return materialRepository.findByCourse_CourseId(courseId);
    }
    
    @Override
    public List<Material> getMaterialsByCourseAndChapter(String courseId, String chapterId) {
        log.info("根据课程ID和章节ID获取资料: courseId={}, chapterId={}", courseId, chapterId);
        return materialRepository.findByCourse_CourseIdAndChapter_ChapterId(courseId, chapterId);
    }
    
    @Override
    public Optional<Material> getMaterialById(String materialId) {
        log.info("根据ID获取资料: {}", materialId);
        return materialRepository.findById(materialId);
    }
    
    @Override
    @Transactional
    public void deleteMaterial(String materialId) {
        log.info("删除资料: {}", materialId);
        
        // 获取资料信息用于删除本地文件
        Optional<Material> materialOpt = materialRepository.findById(materialId);
        if (materialOpt.isPresent()) {
            Material material = materialOpt.get();
            String filePath = material.getMaterialPath();
            
            // 删除数据库记录
            materialRepository.deleteById(materialId);
            
            // 删除本地文件
            if (filePath != null && !filePath.isEmpty()) {
                File file = new File(filePath);
                if (file.exists()) {
                    boolean deleted = file.delete();
                    if (deleted) {
                        log.info("成功删除本地文件: {}", filePath);
                    } else {
                        log.warn("删除本地文件失败: {}", filePath);
                    }
                }
            }
        } else {
            throw new RuntimeException("资料不存在: " + materialId);
        }
    }
    
    @Override
    public boolean validateMaterial(String materialId) {
        return materialRepository.existsById(materialId);
    }
    
    @Override
    public List<String> getMaterialIdsByCourse(String courseId) {
        log.info("根据课程ID获取资料ID列表: {}", courseId);
        return materialRepository.findByCourse_CourseId(courseId)
                .stream()
                .map(Material::getMaterialId)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<String> getMaterialIdsByChapter(String chapterId) {
        log.info("根据章节ID获取资料ID列表: {}", chapterId);
        return materialRepository.findByChapter_ChapterId(chapterId)
                .stream()
                .map(Material::getMaterialId)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Material> getLearnedMaterialsByStudent(String userId, String courseId) {
        log.info("获取学生已学习资料: userId={}, courseId={}", userId, courseId);
        
        try {
            // 调用学习进度服务获取已完成的资料ID列表
            String endpoint = "/api/progress/material/user/" + userId + "/course/" + courseId + "/completed";
            List response = serviceClient.get("learning-progress", endpoint, List.class);
            
            if (response != null) {
                List<String> completedMaterialIds = (List<String>) response;
                // 根据资料ID列表获取资料详情
                return materialRepository.findAllById(completedMaterialIds);
            }
        } catch (Exception e) {
            log.warn("调用学习进度服务失败，返回空列表: {}", e.getMessage());
        }
        
        return List.of();
    }
    
    @Override
    public void markMaterialAsFinished(String userId, String materialId) {
        log.info("标记资料完成: userId={}, materialId={}", userId, materialId);
        
        // 验证资料是否存在
        if (!validateMaterial(materialId)) {
            throw new ResourceNotFoundException("Material", materialId);
        }
        
        try {
            // 调用学习进度服务标记资料完成
            String endpoint = "/api/progress/material/user/" + userId + "/material/" + materialId + "/complete";
            serviceClient.post("learning-progress", endpoint, null, Void.class);
            log.info("资料标记完成成功: userId={}, materialId={}", userId, materialId);
        } catch (Exception e) {
            log.error("调用学习进度服务失败: {}", e.getMessage());
            throw new RuntimeException("标记资料完成失败: " + e.getMessage());
        }
    }
}